﻿using System.Collections.Generic;
using UnityEngine;

namespace UFrame
{
    /// <summary>
    /// 用于UI按钮 不能连续点击, 加一个锁
    /// </summary>
    public class TimeoutMa : MonoBehaviour
    {
        private static TimeoutMa i = null;

        public static TimeoutMa I
        {
            get
            {
                if (i == null)
                {
                    GameObject go = new GameObject("TimeoutMa");
                    i = go.AddComponent<TimeoutMa>();
                    DontDestroyOnLoad(i);
                }

                return i;
            }
        }

        public Dictionary<string, TimeOutInfo> lockDic = new Dictionary<string, TimeOutInfo>();

        public void SetLockInfo(string name, TimeOutInfo info)
        {
            if (lockDic.ContainsKey(name))
                lockDic[name] = info;
            else
                lockDic.Add(name, info);
        }

        public bool IsLock(string name)
        {
            if (lockDic.ContainsKey(name))
            {
                var d = lockDic[name];
                if (d.time > d.counter)
                {
                    d.time = 0;
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                lockDic.Add(name, new TimeOutInfo());
                return false;
            }
        }

        public void FixedUpdate()
        {
            if (lockDic.Count == 0)
                return;

            foreach (var item in lockDic)
            {
                if (item.Value.time <= item.Value.counter)
                    item.Value.time += Time.deltaTime;
            }
        }


        public class TimeOutInfo
        {
            /// <summary>
            /// 毫秒
            /// </summary>
            public double counter = 0.5f;

            /// <summary>
            /// 计时器
            /// </summary>
            public double time = 0;
        }
    }
}